/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utn.tsb.tej.front_end;

import com.trolltech.qt.gui.QCheckBox;
import com.trolltech.qt.gui.QCloseEvent;
import com.trolltech.qt.gui.QComboBox;
import com.trolltech.qt.gui.QDialog;
import com.trolltech.qt.gui.QHBoxLayout;
import com.trolltech.qt.gui.QHeaderView;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QLineEdit;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QTableWidget;
import com.trolltech.qt.gui.QTableWidgetItem;
import com.trolltech.qt.gui.QVBoxLayout;
import csm.uttils.generics.Roster;
import utn.tsb.tej.comunications.Preferences;
import utn.tsb.tej.comunications.server.RoomGame;
import utn.tsb.tej.comunications.server.ThreadWaitingPlayers;
import utn.tsb.tej.world_logic.Color;
import utn.tsb.tej.world_logic.Player;

/**
 *
 * @author Carlos S. Moreno <CarlosS.Moreno@gmail.com>
 */
public class NewRoomGameWindow extends QDialog {

    RoomGame room;
    Player me;
    ThreadWaitingPlayers threadWaiting;
    QPushButton btnStart, btnCreate, btnRefresh;
    QLineEdit txtRoomName, txtNickname;
    QLabel lblRoomName;
    QTableWidget tablePlayers;
    QComboBox cmbPlayersCant, cmbColors;
    QCheckBox chkReady;

    public NewRoomGameWindow() {
        initComponents();

        cmbColors.currentIndexChanged.connect(this, "cmbColors_currentIndexChanged()");
        
        me = new Player();
        me.setNickName(Preferences.getNickname());

        txtNickname.setText(me.getNickName());
        txtRoomName.selectAll();
    }

    private void initComponents() {
        this.setWindowTitle("T.E.J. - New Room Game");
        this.setMinimumSize(600, 320);
        this.setMaximumSize(0, 0);

        QVBoxLayout mainLayout = new QVBoxLayout(this);

        //Label and Button for changing the room name
        QHBoxLayout changeNameLayout = new QHBoxLayout();

        QLabel lblRoomTitle = new QLabel("Nombre de la Sala:");
        lblRoomTitle.setMaximumWidth(120);
        //the actual room name
        txtRoomName = new QLineEdit("New TEJ Room Game");
        lblRoomName = new QLabel();
        lblRoomName.setStyleSheet("color:#990000");
        lblRoomName.setVisible(false);

        QLabel lblAllowedPlayers = new QLabel("Cantidad de Jugadores:");
        lblAllowedPlayers.setFixedWidth(150);
        cmbPlayersCant = new QComboBox();
        cmbPlayersCant.addItem("2");
        cmbPlayersCant.addItem("3");
        cmbPlayersCant.addItem("4");
        cmbPlayersCant.addItem("5");
        cmbPlayersCant.addItem("6");
        cmbPlayersCant.setCurrentIndex(4);
        cmbPlayersCant.currentIndexChanged.connect(this,
                "cmbPlayersCant_currentIndexChanged()");
        cmbPlayersCant.setFixedWidth(45);

        changeNameLayout.addWidget(lblRoomTitle);
        changeNameLayout.addWidget(lblRoomName);
        changeNameLayout.addWidget(txtRoomName);
        changeNameLayout.addWidget(lblAllowedPlayers);
        changeNameLayout.addWidget(cmbPlayersCant);

        //Adding the layout to the main layout
        mainLayout.addLayout(changeNameLayout);

        //Layout Player's Data
        QHBoxLayout userLayout = new QHBoxLayout();
        txtNickname = new QLineEdit(Preferences.getNickname());
        txtNickname.editingFinished.connect(this, "txtNickname_editingFinished()");
        cmbColors = new QComboBox();
        cmbColors.setEnabled(false);
        userLayout.addWidget(new QLabel("Jugador:"));
        userLayout.addWidget(txtNickname);
        userLayout.addWidget(new QLabel("Color:"));
        userLayout.addWidget(cmbColors);

        mainLayout.addLayout(userLayout);


        QLabel lblPlayers = new QLabel("Jugadores Conectados:");

        //Adding the label to the main layout
        mainLayout.addWidget(lblPlayers);

        //Players Table
        tablePlayers = new QTableWidget(6, 5);
        tablePlayers.horizontalHeader().setResizeMode(QHeaderView.ResizeMode.Fixed);
        tablePlayers.setHorizontalHeaderItem(0, new QTableWidgetItem("Nº"));
        tablePlayers.setHorizontalHeaderItem(1, new QTableWidgetItem("Tipo"));
        tablePlayers.setHorizontalHeaderItem(2, new QTableWidgetItem("Jugador"));
        tablePlayers.setHorizontalHeaderItem(3, new QTableWidgetItem("Color"));
        tablePlayers.setHorizontalHeaderItem(4, new QTableWidgetItem("Listo"));
        tablePlayers.setColumnWidth(0, 40);
        tablePlayers.setColumnWidth(1, 80);
        tablePlayers.setColumnWidth(2, 360);
        tablePlayers.setColumnWidth(3, 50);
        tablePlayers.setColumnWidth(4, 50);
        tablePlayers.verticalHeader().setResizeMode(QHeaderView.ResizeMode.ResizeToContents);
        tablePlayers.horizontalHeader().setStretchLastSection(true);
//        tablePlayers.horizontalHeader().hide();
        tablePlayers.verticalHeader().hide();

        //adding the table
        mainLayout.addWidget(tablePlayers);

        //start and ready layout
        QHBoxLayout startLayout = new QHBoxLayout();

        //Create button
        btnCreate = new QPushButton("Crear Sala");
        btnCreate.clicked.connect(this, "btnCreate_clicked()");
        btnCreate.setMaximumWidth(150);

        //Start button
        btnStart = new QPushButton("Comenzar Juego");
        btnStart.setMaximumWidth(150);
        btnStart.setVisible(false);
        btnStart.setEnabled(false);
        chkReady = new QCheckBox("Estoy Listo!");
        chkReady.stateChanged.connect(this, "chkReady_stateChanged()");
        QIcon icon = new QIcon(getClass().getResource("/images/update.png").getPath());
        btnRefresh = new QPushButton(icon, "");
        btnRefresh.setMaximumWidth(32);
        btnRefresh.setEnabled(false);
        btnRefresh.clicked.connect(this, "btnRefresh_clicker()");

        startLayout.addWidget(btnCreate);
        startLayout.addWidget(btnStart);
        startLayout.addWidget(chkReady);
        startLayout.addWidget(btnRefresh);

        //Adding the start lay out to the main layout
        mainLayout.addLayout(startLayout);
    }

    private void initiateRoom() {
        RoomGame.setInstance(room);
        threadWaiting = new ThreadWaitingPlayers("New_Room_Game");
        me.setColor(room.getAnAvailableColor());
        me.setAddress("0.0.0.0");
        room.addPlayer(me);
        //loadColors();
    }

    private void cmbPlayersCant_currentIndexChanged() {
    }

    public void closeEvent(QCloseEvent event) {
        threadWaiting.stopWaiting();
    }

    public void saveData() {
        room = new RoomGame();
        room.setRoomName(txtRoomName.text());
        room.setMaxPlayers(Integer.parseInt(cmbPlayersCant.currentText()));
        initiateRoom();
    }

    private void btnCreate_clicked() {

        txtRoomName.setEnabled(false);
        txtRoomName.setVisible(false);
        lblRoomName.setText(txtRoomName.text());
        lblRoomName.setVisible(true);
        cmbPlayersCant.setEnabled(false);
        btnCreate.setEnabled(false);
        btnCreate.setVisible(false);
        btnStart.setVisible(true);
        btnRefresh.setEnabled(true);
        cmbColors.setEnabled(true);

        saveData();
        //And finally it start the Thread
        threadWaiting.start();
        updateWindowData();
    }

    private void updateWindowData() {
        loadColors();
        udpateTable();
    }

    private void udpateTable() {
        tablePlayers.clearContents();
        Roster<Player> players = RoomGame.getInstance().getPlayers();
        players.startIterator();

        Player otherPlayer;
        int r = 0;
        while (players.hasNext()) {
            otherPlayer = players.next();
            tablePlayers.setCellWidget(r, 0, new QLabel(String.valueOf(r + 1)));//Number
            if (otherPlayer.getType() == Player.TYPE_CPU)//Type
            {
                tablePlayers.setCellWidget(r, 1, new QLabel("CPU"));
            } else {
                tablePlayers.setCellWidget(r, 1, new QLabel("User"));
            }
            tablePlayers.setCellWidget(r, 2, new QLabel(otherPlayer.getNickName()));//Player
            QIcon colorIcon = getColorIcon(otherPlayer.getColor().getCodeRGB());
            tablePlayers.setItem(r, 3, new QTableWidgetItem(colorIcon, ""));//Color

            QIcon ready;
            if (otherPlayer.isReady()) {
                ready = new QIcon(getClass().getResource("/images/ready.png").getPath());
            } else {
                ready = new QIcon(getClass().getResource("/images/not_ready.png").getPath());
            }
            tablePlayers.setItem(r, 4, new QTableWidgetItem(ready, ""));//Color
            r++;
        }
    }

    private QIcon getColorIcon(String rgb) {
        QIcon icon = new QIcon();
        if (rgb.compareToIgnoreCase(Color.RED) == 0) {
            icon = new QIcon(getClass().getResource("/images/Red_Ball1.png").getPath());
        }
        if (rgb.compareToIgnoreCase(Color.BLACK) == 0) {
            icon = new QIcon(getClass().getResource("/images/Black_Ball1.png").getPath());
        }
        if (rgb.compareToIgnoreCase(Color.GREEN) == 0) {
            icon = new QIcon(getClass().getResource("/images/Green_Ball1.png").getPath());
        }
        if (rgb.compareToIgnoreCase(Color.BLUE) == 0) {
            icon = new QIcon(getClass().getResource("/images/Blue_Ball1.png").getPath());
        }
        if (rgb.compareToIgnoreCase(Color.WHITE) == 0) {
            icon = new QIcon(getClass().getResource("/images/Fuccia_Ball1.png").getPath());
        }
        if (rgb.compareToIgnoreCase(Color.YELLOW) == 0) {
            icon = new QIcon(getClass().getResource("/images/Yellow_Ball1.png").getPath());
        }
        return icon;
    }

    private void loadColors() {
        cmbColors.clear();
        cmbColors.addItem(getColorIcon(me.getColor().getCodeRGB()),
                me.getColor().toString(),
                me.getColor());

        Roster<Color> colors = room.getAllAvailableColors();
        colors.startIterator();
        while (colors.hasNext() && cmbColors.count() <= colors.count()) {
            Color color = colors.next();
            cmbColors.addItem(getColorIcon(color.getCodeRGB()),
                    color.toString(),
                    color);
        }
    }

    private void chkReady_stateChanged() {
        txtNickname.setEnabled(!chkReady.isChecked());
        cmbColors.setEnabled(!chkReady.isChecked());
        me.setReady(chkReady.isChecked());
        updateWindowData();
    }

    private void txtNickname_editingFinished() {
        if (me.getNickName().compareTo(txtNickname.text()) != 0){
        me.setNickName(txtNickname.text());
        updateWindowData();
        }
    }

    private void cmbColors_currentIndexChanged() {
        Color newColor = (Color) cmbColors.itemData(cmbColors.currentIndex());
        if (cmbColors.currentIndex() > -1 && me.getColor().compareTo(newColor) != 0 && room.isColorAvailable(newColor)) {
            room.addColor(me.getColor());
            me.setColor(newColor);
            room.removeColor(newColor);
        }
        updateWindowData();
    }

    private void btnRefresh_clicker()
    {
        updateWindowData();
    }
}
